import { HttpConfig } from './HttpConfig';
import { HttpTokenManager } from './HttpTokenManager';
import { HttpQueue } from './HttpQueue';
import { HttpStorage } from './HttpStorage';
import { PlatformAdapter } from './PlatformAdapter';

export interface ApiResponse<T> {
  msg: string;
  time: number;
  data: T;
}

async function request<T>(method: string, url: string, data?: any, options: { skipAuth?: boolean } = {}) {
  const fullUrl = HttpConfig.baseURL + url;
  const headers = { ...HttpConfig.headers };

  if (!options.skipAuth) {
    const token = HttpStorage.get('token');
    if (token) headers['ba-user-token'] = `${token}`;
  }

  console.log("headers", JSON.stringify(headers));

  const doRequest = async (): Promise<T> => {
    const response = await PlatformAdapter.request<ApiResponse<T>>(method, fullUrl, data, headers);
    return response.data;
  };

  try {
    return await doRequest();
  } catch (err: any) {
    console.log("request error", err);
    if (err?.status === 303 && !options.skipAuth) {
      HttpQueue.add(() => request<T>(method, url, data, options));
      await HttpTokenManager.handleAuthError();
    } else {
      throw err;
    }
  }
}

export const Http = {
  get: <T>(url: string, params?: any, opt = {}) => request<T>('GET', url, params, opt),
  post: <T>(url: string, data?: any, opt = {}) => request<T>('POST', url, data, opt),
  put: <T>(url: string, data?: any, opt = {}) => request<T>('PUT', url, data, opt),
  delete: <T>(url: string, data?: any, opt = {}) => request<T>('DELETE', url, data, opt)
};
